/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.workflow.controller.procerss;

import com.alibaba.fastjson2.JSON;
import com.je.bpm.model.process.results.ProcessCirculatedElementResult;
import com.je.bpm.runtime.shared.operator.validator.PayloadValidErrorException;
import com.je.common.base.document.ContentTypeSuffixEnum;
import com.je.common.base.mapper.query.Query;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.ibatis.extension.plugins.pagination.Page;
import com.je.workflow.service.button.ButtonService;
import com.je.workflow.service.model.ModelService;
import com.je.workflow.service.usertask.ProcessInfoService;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * 流程按钮操作控制层
 */

@RestController
@RequestMapping(value = "/je/workflow/processInfo")
public class ProcessInfoController extends AbstractPlatformController {

    @Autowired
    private ProcessInfoService processInfoService;
    @Autowired
    private ButtonService buttonService;
    @Autowired
    private ModelService modelService;

    @Override
    @RequestMapping(value = "/load", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult load(BaseMethodArgument param, HttpServletRequest request) {
        if (param.getLimit() == 0) {
            param.setLimit(-1);
        }

        //分页对象
        Page page = new Page<>(param.getPage(), param.getLimit());
        String funcCode = param.getFuncCode();
        //构建查询条件
        Query query = param.buildQuery();
        commonService.buildProductQuery(query, "SY_PRODUCT_ID");
        param.setjQuery(JSON.toJSONString(query));
        ConditionsWrapper wrapper = manager.buildWrapper(param, request);
        List<Map<String, Object>> list = metaService.load(funcCode, page, wrapper);
        return BaseRespResult.successResultPage(list, Long.valueOf(page.getTotal()));
    }

    /**
     * 获取表单流程按钮和表单控制信息
     */
    @RequestMapping(value = "/preview", method = RequestMethod.GET)
    @ApiResponses({
            @ApiResponse(code = 200, response = File.class, message = ""),
    })
    public ResponseEntity<InputStream> preview(String beanId, HttpServletRequest request) throws FileNotFoundException {
        String pdid = getStringParameter(request, "pdid");
        File file = modelService.generateImage(beanId, pdid);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, ContentTypeSuffixEnum.S_png.getContentType())
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName())
                .body(new FileInputStream(file));
    }

    /**
     * 获取流程图列表
     */
    @RequestMapping(value = "/getProcessPlanningList", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getProcessPlanningList(String funcCode, String beanId) {
        List<Map<String, String>> result = modelService.getProcessPlanningList(funcCode, beanId);
        return BaseRespResult.successResult(result);
    }

    /**
     * 获取表单流程按钮和表单控制信息
     */
    @RequestMapping(value = "/getInfo", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getInfo(BaseMethodArgument param, HttpServletRequest request) {
        String prod = getStringParameter(request, "prod");
        String beanId = getStringParameter(request, "beanId");
        String tableCode = param.getTableCode();
        String funcCode = param.getFuncCode();
        return BaseRespResult.successResult(buttonService.getButtons(prod, tableCode, funcCode, beanId));
    }

    /**
     * 获取提交的节点信息和人员信息
     */
    @RequestMapping(value = "/getSubmitOutGoingNode", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getSubmitOutGoingNode(BaseMethodArgument param, HttpServletRequest request) {
        String taskId = getStringParameter(request, "taskId");
        String pdid = getStringParameter(request, "pdid");
        String prod = getStringParameter(request, "prod");
        String beanId = getStringParameter(request, "beanId");
        String tableCode = getStringParameter(request, "tableCode");
        return BaseRespResult.successResult(processInfoService.getSubmitOutGoingNode(taskId, pdid, prod, beanId, tableCode));
    }

    /**
     * 获取提交的节点信息和人员信息
     */
    @RequestMapping(value = "/getSubmitOutGoingNodeAssignee", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getSubmitOutGoingNodeAssignee(BaseMethodArgument param, HttpServletRequest request) {
        String taskId = getStringParameter(request, "taskId");
        String pdid = getStringParameter(request, "pdid");
        String beanId = getStringParameter(request, "beanId");
        String target = getStringParameter(request, "target");
        String prod = getStringParameter(request, "prod");
        String tableCode = getStringParameter(request, "tableCode");
        String operationId = getStringParameter(request, "operationId");
        return BaseRespResult.successResult(processInfoService.getSubmitOutGoingNodeAssignee(taskId, pdid, prod, beanId, target, tableCode, operationId));
    }

    /**
     * 获取常用人员
     */
    @RequestMapping(value = "/getFrequentlyUsedContacts", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getFrequentlyUsedContacts(BaseMethodArgument param, HttpServletRequest request) {
        return BaseRespResult.successResult(processInfoService.commonUserInfo());
    }


    /**
     * 获取退回节点名称
     */
    @RequestMapping(value = "/getGobackNode", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getGobackNode(BaseMethodArgument param, HttpServletRequest request) {
        String piid = getStringParameter(request, "piid");
        String taskId = getStringParameter(request, "taskId");
        return BaseRespResult.successResult(processInfoService.getGobackNode(piid, taskId));
    }

    /**
     * 获取取回节点名称
     */
    @RequestMapping(value = "/getRetrieveNode", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getRetrieveNode(BaseMethodArgument param, HttpServletRequest request) {
        String piid = getStringParameter(request, "piid");
        String taskId = getStringParameter(request, "taskId");
        return BaseRespResult.successResult(processInfoService.getRetrieveNode(piid, taskId));
    }

    /**
     * 获取委托节点信息
     */
    @RequestMapping(value = "/getDelegationNode", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getDelegationNode(BaseMethodArgument param, HttpServletRequest request) {
        String piid = getStringParameter(request, "piid");
        String taskId = getStringParameter(request, "taskId");
        return BaseRespResult.successResult(processInfoService.getDelegationNode(piid, taskId));
    }

    /**
     * 获取驳回信息
     */
    @RequestMapping(value = "/getDismissOutGoingNode", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getDismissOutGoingNode(BaseMethodArgument param, HttpServletRequest request) {
        String piid = getStringParameter(request, "piid");
        String taskId = getStringParameter(request, "taskId");
        String pdid = getStringParameter(request, "pdid");
        return BaseRespResult.successResult(processInfoService.getDismissOutGoingNode(piid, taskId, pdid));
    }

    /**
     * 获取直送节点名称
     */
    @RequestMapping(value = "/getDirectDeliveryNode", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getDirectDeliveryNode(BaseMethodArgument param, HttpServletRequest request) {
        String piid = getStringParameter(request, "piid");
        String taskId = getStringParameter(request, "taskId");
        return BaseRespResult.successResult(processInfoService.getDirectDeliveryNode(piid, taskId));
    }

    /**
     * 获取流程传阅人
     */
    @RequestMapping(value = "/getPassRoundUsers", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getPassRoundUsers(BaseMethodArgument param, HttpServletRequest request) {
        String taskId = getStringParameter(request, "taskId");
        String beanId = getStringParameter(request, "beanId");
        String prod = getStringParameter(request, "prod");
        String tableCode = getStringParameter(request, "tableCode");
        ProcessCirculatedElementResult processCirculatedElementResult = null;
        try {
            processCirculatedElementResult = processInfoService.getPassRoundUsers(taskId, prod, beanId, tableCode);
        } catch (PayloadValidErrorException e) {
            e.printStackTrace();
        }
        return BaseRespResult.successResult(processCirculatedElementResult.getEntity().getAllUserInfo());
    }

    /**
     * 获取流程传阅人
     */
    @RequestMapping(value = "/getPassRoundUsersListByTaskId", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getPassRoundUsersListByTaskId(BaseMethodArgument param, HttpServletRequest request) {
        String taskId = getStringParameter(request, "taskId");
        String userId = getStringParameter(request, "userId");
        List<Map<String, String>> list = processInfoService.getPassRoundUsersListByTaskId(taskId, userId);
        return BaseRespResult.successResult(list);
    }

    /**
     * 获取会签操作人员信息
     */
    @RequestMapping(value = "/getCounterSignerOperationalUsers", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getCounterSignerOperationalUsers(BaseMethodArgument param, HttpServletRequest request) {
        String taskId = getStringParameter(request, "taskId");
        return BaseRespResult.successResult(processInfoService.getCounterSignerOperationalUsers(taskId));
    }

    /**
     * 获取会签审批意见
     */
    @RequestMapping(value = "/getCountersignApprovalOpinion", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getCountersignApprovalOpinion(BaseMethodArgument param, HttpServletRequest request) {
        String taskId = getStringParameter(request, "taskId");
        return BaseRespResult.successResult(processInfoService.getCountersignApprovalOpinion(taskId));
    }


    /**
     * 获取当前节点处理人
     */
    @RequestMapping(value = "/getAssigneeByTaskId", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getAssigneeByTaskId(BaseMethodArgument param, HttpServletRequest request) {
        String taskId = getStringParameter(request, "taskId");
        String currentNodeId = getStringParameter(request, "currentNodeId");
        return BaseRespResult.successResult(processInfoService.getAssigneeByTaskId(taskId, currentNodeId));
    }

    /**
     * 获取我催办的数据
     *
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "/getUrgeData", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getUrgeData(BaseMethodArgument param, HttpServletRequest request) {
        String piid = getStringParameter(request, "piid");
        String taskId = getStringParameter(request, "taskId");
        String currentNodeId = getStringParameter(request, "currentNodeId");
        String type = getStringParameter(request, "type");
        Page page = new Page(param.getPage(), param.getLimit());
        page = processInfoService.getUrgeData(page, taskId, piid, currentNodeId, type);
        return BaseRespResult.successResultPage(page.getRecords(), (long) page.getTotal());
    }


}
